<?php
namespace app\common\model;

use think\facade\Db;
use hema\device\Driver;

/**
 * 云设备模型
 */
class Device extends BaseModel
{
    // 定义表名
    protected $name = 'device';

    // 定义主键
    protected $pk = 'device_id';

    // 追加字段
    protected $append = [
        'status'
    ];

    /**
     * 关联门店表
     */
    public function shop()
    {
        return $this->belongsTo('app\\common\\model\\Shop');
    }

    /**
     * 类型
     */
    public function getDevTypeAttr($value)
    {
        $status = [
            'mstching' => '猫猫云打印机', 
            'feieyun' => '飞鹅云打印机', 
            'yilianyun' => '易联云打印机', 
            'hmcalling' => '河马云叫号器'
        ];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 状态
     */
    public function getIsOpenAttr($value)
    {
        $status = ['关闭','开启'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 获取器: 转义数组格式
     */
    public function getValuesAttr($value)
    {
        return json_decode($value, true);
    }

    /**
     * 修改器: 转义成json格式
     */
    public function setValuesAttr($value)
    {
        return json_encode($value);
    }

    /**
     * 设备联网状态 - 自动完成
     * 返回数据格式："}{"State":0,"Code":200,"Message":"成功"}
     *State:状态值(-1错误 0正常 1缺纸 2温度保护报警 3 忙碌 4 离线)
     */
    public function getStatusAttr($value,$data)
    {
        $parameter['applet_id'] = $data['applet_id'];
        if($data['dev_type'] == 'mstching'){
            $parameter['dev_key'] = $data['dev_key'];
        }else{
            $parameter['dev_id'] = $data['dev_id'];
        }
        $dev = new Driver([],$parameter,0,$data['dev_type']);
        return $dev->status();
    }

    /**
     * 获取列表
     */
    public function getList($shop_id = 0, $is_open = null)
    {
        // 筛选条件
        $filter = [];
        $shop_id > 0 && $filter['shop_id'] = $shop_id;
        !is_null($is_open) && $filter['is_open'] = $is_open;
        // 排序规则
        $sort = ['device_id' => 'desc']; 
         // 执行查询
        return $this->with(['shop'])->where($filter)->order($sort)->select();
    }

    /**
     * 播报语音
     * $mode = 模式(new=新订单提醒,pay=微信到账提醒) ，$row_no=参数,
     */
    public static function push($shop_id,$mode,$row_no='')
    {
        if($call = self::get(['shop_id' => $shop_id,'dev_type' => 'hmcalling','is_open' => 1])){
            if(!empty($type)){
                if($mode == 'pay' AND $call['values']['is_pay'] == 0){
                    return true; //未开启直接退出
                }
                if($mode == 'new' AND $call['values']['is_new'] == 0){
                    return true; //未开启直接退出
                }
            }
            $dev = new Driver([],[
                'dev_id' => $call['dev_id'],
                'mode' => $mode,
                'row_no' => $row_no
            ],0,'hmcalling');
            $dev->push();
        }
        return true;
    }

    /**
     * 打印小票
     * $data 打印的数据
     * $tpl 模板类型 0=订单模板 1=退单模板
     */
    public static function print($data, $tpl=0)
    {
        //获取门店打印机列表
        if($list = self::where(['shop_id' => $data['shop_id'],'is_open' => 1])->select()){
            //如果有设备
            for($n=0;$n<sizeof($list);$n++){
                $dev = new Driver($list[$n],$data,$tpl);
                $dev->print();
            }
        }
        return true;
    }
    
    /**
     * 用户设备绑定
     */
    public function add($data)
    {
        $data['applet_id'] = self::$applet_id;
        // 开启事务
        Db::startTrans();
        try {
            //对对机
            if($data['dev_type']=='mstching'){
                if(strlen($data['dev_key'])!= 16){
                    $this->error = '设备编号应该为16位';
                    return false;
                }
                //查询设备是否已经添加
                if($this->get([
                    'dev_key' => $data['dev_key'],
                    'dev_type' => 'mstching'
                ])){
                    $this->error = '该设备已被添加，不可重复';
                    return false;
                }
                //实例化
                $dev = new Driver([],$data,0,'mstching');
                $result = $dev->add();
                if($result['Code']!=200){//绑定不成功
                    $this->error = $result['Message'];
                    return false;
                }   
                $data['dev_id'] = $result['OpenUserId'];
            }
            //飞鹅
            if($data['dev_type']=='feieyun'){
                if(strlen($data['dev_id'])!= 9){
                    $this->error = '设备编号应该为9位';
                    return false;
                }
                if(strlen($data['dev_key'])!= 8){
                    $this->error = '设备编号应该为8位';
                    return false;
                }
                //查询设备是否已经添加
                if($this->get([
                    'dev_id' => $data['dev_id'],
                    'dev_type' => 'feieyun'
                ])){
                    $this->error = '该设备已被添加，不可重复';
                    return false;
                }
                $dev = new Driver([],$data,0,'feieyun');
                $result = $dev->add();
                if($result['ret']!=0){
                    $this->error = $result['msg'];
                    return false;
                }
            }
            //易联云
            if($data['dev_type']=='yilianyun'){
                if(strlen($data['dev_id'])!= 10){
                    $this->error = '设备编号应该为10位';
                    return false;
                }
                if(strlen($data['dev_key'])!= 12){
                    $this->error = '设备编号应该为12位';
                    return false;
                }
                //查询设备是否已经添加
                if($this->get([
                    'dev_id' => $data['dev_id'],
                    'dev_type' => 'yilianyun'
                ])){
                    $this->error = '该设备已被添加，不可重复';
                    return false;
                }
                $dev = new Driver([],$data,0,'yilianyun');
                $result = $dev->add();
                if($result['error']!=0){
                    $this->error = $result['error_description'];
                    return false;
                }
            }
            //云叫号
            if($data['dev_type']=='hmcalling'){
                if(strlen($data['dev_id'])!= 8){
                    $this->error = '设备编号应该为8位';
                    return false;
                }
                if(strlen($data['dev_key'])!= 16){
                    $this->error = '设备密钥应该为16位';
                    return false;
                }
                //查询设备是否已经添加
                if($this->get([
                    'dev_id' => $data['dev_id'],
                    'dev_type' => 'hmcalling'
                ])){
                    $this->error = '该设备已被添加，不可重复';
                    return false;
                }
                if($this->get([
                    'shop_id' => $data['shop_id'],
                    'dev_type' => 'hmcalling'
                ])){
                    $this->error = '每个门店只能添加一台！';
                    return false;
                }
                $dev = new Driver([],$data,0,'hmcalling');
                $result = $dev->add();
                if($result['code'] != 0){
                    $this->error = $result['msg'];
                    return false;
                }
                if($data['values']['volume'] < 15){
                    $dev = new Driver([],[
                        'dev_id' => $call['dev_id'],
                        'mode' => 'volume',
                        'row_no' => $data['values']['volume']
                    ],0,'hmcalling');
                    $result = $dev->push();
                    if($result['code'] != 0){
                        $this->error = $result['msg'];
                        return false;
                    }
                }
            }
            $this->save($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 更新
     */
    public function edit($data)
    {
        //云叫号器
        if($this['dev_type']['value'] == 'hmcalling' AND get_addon_info('hmcalling') AND $this['values']['volume'] != $data['values']['volume']){
            $dev = new Driver([],[
                'dev_id' => $this->dev_id,
                'mode' => 'volume',
                'row_no' => $data['values']['volume']
            ],0,'calling');
            $result = $dev->push();
            if($result['code'] != 0){
                $this->error = $result['msg'];
                return false;
            }
        }
        return $this->save($data) !== false;
    }

    /**
     * 删除
     */
    public function remove() {
        // 开启事务
        Db::startTrans();
        try {
            //飞鹅
            if($this['dev_type']['value'] == 'feieyun'){
                $dev = new Driver([],[
                    'dev_id' => $this->dev_id,
                    'applet_id' => $this->applet_id
                ],0,'feieyun');
                $result = $dev->delete();
                if($result['ret']!=0){
                    $this->error = $result['msg'];
                    return false;
                }
            }
            //易联云
            if($this['dev_type']['value'] == 'yilianyun'){
                $dev = new Driver([],[
                    'dev_id' => $this->dev_id,
                    'applet_id' => $this->applet_id
                ],0,'feieyun');
                $result = $dev->delete();
                if($result['error']!=0){
                    $this->error = $result['error_description'];
                    return false;
                }
            }
            //河马云叫号
            if($this['dev_type']['value'] == 'hmcalling'){
                $dev = new Driver([],[
                    'dev_id' => $this->dev_id,
                    'applet_id' => $this->applet_id
                ],0,'hmcalling');
                $result = $dev->delete();
                if($result['code'] != 0){
                    $this->error = $result['msg'];
                    return false;
                }
            }
            $this->delete();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 状态
     */
    public function statu()
    {
        $this->is_open['value'] ? $this->is_open = 0 : $this->is_open = 1;
        return $this->save();
    }
}